<?php


namespace app\admin\controller\v1;

use app\admin\model\CategoryModel;
use app\admin\Validate\category\AddCategoryValidate;
use app\admin\Validate\category\CategoryListByPageValidate;
use app\admin\Validate\category\UpdateCategoryValidate;
use app\BaseController;
use app\common\Token;

/**
 * 分类
 * Class Category
 * @package app\admin\controller\v1
 */
class Category extends BaseController
{
    /**
     * 添加分类
     * @return \think\response\Json
     */
    public function addCategory()
    {
        Token::checkToken($this->request);
        $param = (new AddCategoryValidate())->validateParam();
        $model = new CategoryModel();
        $result = $model->save(
            [
                "category_name" => $param['category_name'],
                "category_route" => $param['category_route'],
                "px" => $param['px'],
                "status" => $param['status'] ?? -1,
                "add_time" => getDateTime(),
            ]
        );
        if ($result) {
            return successJson(true, "添加成功");
        }
        return errorJson(60001, "添加失败");
    }

    /**
     * 后台获取所有的Category，需要Token
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function getAllCategoryPage()
    {
        Token::checkToken($this->request);
        $param = (new CategoryListByPageValidate)->validateParam();
        $model = new CategoryModel();
        $re = $model->toPaginate($param, [
//            'status'=>['menu_name', 'like', "%$menu_name%"],
        ]);
        return successJson($re);
    }

    /**
     * 获取所有状态为启动的Category
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAllCategory() {
        Token::checkToken($this->request);
        $model = new CategoryModel();
        $re = $model->where('status', '=', 1)->select();
        return successJson($re);
    }

    /**
     * 更新数据
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function updateCategory()
    {
        Token::checkToken($this->request);
        $param = (new UpdateCategoryValidate())->validateParam();
        $model = new CategoryModel();
        $re = $model->find($param['id'])
            ->save($param);
        if($re){
            return successJson(true);
        }
        return errorJson(60004,"更新失败");
    }

    public function deleteCategory(int $id) {
        Token::checkToken($this->request);
        $success = CategoryModel::destroy($id);
        if($success){
            return successJson(true);
        }
        return errorJson(60004,"删除失败");
    }
}